<template>
  <div class="attrFrom">
    <el-form
      ref="formDynamic"
      v-loading="loading"
      size="small"
      :model="formDynamic"
      :rules="rules"
      class="attrFrom mb20"
      label-width="100px"
      @submit.native.prevent
    >
      <el-row :gutter="24">
        <el-col v-bind="grid">
          <el-form-item label="规格名称：" prop="ruleName">
            <el-input v-model="formDynamic.ruleName" maxlength="20" placeholder="请输入标题名称" />
          </el-form-item>
        </el-col>

        <el-col v-for="(item, index) in formDynamic.ruleValue" :key="item + index" :span="24">
          <el-form-item>
            <div class="acea-row">
              <span class="mr5">{{ item.attrName }}</span>
              <i class="el-icon-circle-close" @click="handleRemove(index)" />
            </div>
            <div class="rulesBox">
              <el-tag
                v-for="(tagItem, tagIndex) in item.attrValue"
                :key="tagItem + tagIndex"
                size="medium"
                closable
                :disable-transitions="disableTransitions"
                class="mb5 mr10"
                @close="handleClose(item.attrValue, tagIndex)"
              >
                {{ tagItem }}
              </el-tag>
              <el-input
                v-if="item.inputVisible"
                ref="saveTagInput"
                v-model="item.attrValue.attrsVal"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="$event.target.blur"
                @blur="createAttr(item.attrValue.attrsVal, index)"
              />
              <el-button v-else class="button-new-tag" size="small" icon="el-icon-plus" @click="showInput(item)">添加</el-button>
            </div>
          </el-form-item>
        </el-col>

        <el-col v-if="isBtn" :span="24" class="mt10" style="padding-left: 0;padding-right: 0;">
          <el-col v-bind="grid">
            <el-form-item label="规格：">
              <el-input v-model="attrsName" maxlength="20" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid">
            <el-form-item label="规格值：">
              <el-input v-model="attrsVal" maxlength="20" placeholder="请输入规格值" />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid">
            <el-form-item>
              <el-button type="primary" size="small" class="mr10" @click="createAttrName">确定</el-button>
              <el-button size="small" @click="offAttrName">取消</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button v-if="!isBtn" type="primary" icon="el-icon-plus" @click="isBtn = true">添加新规格</el-button>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button size="small" @click="resetForm('formDynamic')">取消</el-button>
      <el-button type="primary" size="small" :loading="loadingBtn" @click="handleSubmit('formDynamic')">确定</el-button>
    </div>
  </div>
</template>

<script>
import { attrCreatApi, attrEditApi } from '@/api/store'

export default {
  name: 'AttrFrom',
  props: {
    // 当前行
    currentRow: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      grid: {
        xl: 8,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 24
      },
      loading: false,
      loadingBtn: false,
      formDynamic: {
        ruleName: '',
        ruleValue: []
      },
      // 验证
      rules: {
        ruleName: [
          { required: true, message: '请输入规格名称', trigger: 'blur' }
        ]
      },
      // 规格名称
      attrsName: '',
      // 规格值
      attrsVal: '',
      // 是否禁用Tag关闭动画
      disableTransitions: false,
      // 添加规格属性
      isBtn: false
    }
  },
  watch: {
    currentRow: {
      handler: function(val, oldVal) {
        this.formDynamic = val
      },
      immediate: true
    }
  },
  methods: {
    // 删除整个节点
    handleRemove(index) {
      this.formDynamic.ruleValue.splice(index, 1)
    },
    // 关闭Tag
    handleClose(item, index) {
      item.splice(index, 1)
    },
    // 提交按钮
    handleSubmit(name) {
      const ID = this.formDynamic.id
      const data = {
        ruleName: this.formDynamic.ruleName,
        ruleValue: this.formDynamic.ruleValue
      }
      ID ? data.id = ID : data

      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formDynamic.ruleValue.length === 0) {
            return this.$message.warning('请至少添加一条属性规格！')
          }

          this.loading = true
          this.loadingBtn = true
          setTimeout(() => {
            ID ? this.attrEditApi(data) : this.attrCreatApi(data)
          }, 1500)
        } else {
          this.loading = false
          this.loadingBtn = false
        }
      })
    },
    // 编辑属性规则API
    attrEditApi(data) {
      data.ruleValue.forEach((item) => {
        item.attrValue = item.attrValue.join(',')
        delete item.inputVisible
      })
      data.ruleValue = JSON.stringify(data.ruleValue)
      attrEditApi(data).then(res => {
        this.$message.success('提交成功!')
        this.$msgbox.close()
        this.clear()
        this.$emit('getList')
        this.loading = false
        this.loadingBtn = false
      }).catch(err => {
        this.loading = false
        this.loadingBtn = false
      })
    },
    // 创建属性规则API
    attrCreatApi(data) {
      data.ruleValue.forEach((item) => {
        item.attrValue = item.attrValue.join(',')
        delete item.inputVisible
      })
      data.ruleValue = JSON.stringify(data.ruleValue)

      attrCreatApi(data).then(res => {
        this.$message.success('提交成功')
        this.$msgbox.close()
        this.clear()
        this.$emit('getList')
        this.loading = false
        this.loadingBtn = false
      }).catch(() => {
        this.loading = false
        this.loadingBtn = false
      })
    },
    // 显示Tag规格
    showInput(item) {
      this.$set(item, 'inputVisible', true)
      this.$nextTick(() => {
        this.$refs.saveTagInput[0].focus()
      })
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.formDynamic.ruleValue[idx].attrValue.push(num)
        const hash = {}
        this.formDynamic.ruleValue[idx].attrValue = this.formDynamic.ruleValue[idx].attrValue.reduce((item, next) => {
          if (hash[next]) {
            this.$message.warning('规格属性已存在!')
          } else {
            hash[next] = true && item.push(next)
          }
          return item
        }, [])
        this.formDynamic.ruleValue[idx].inputVisible = false
      } else {
        this.$message.warning('请添加属性')
      }
    },
    // 关闭弹框
    resetForm(formName) {
      this.$msgbox.close()
      this.clear()
      this.$refs[formName].resetFields()
    },
    // 清空
    clear() {
      this.$refs['formDynamic'].resetFields()
      this.formDynamic.ruleValue.splice(0, this.formDynamic.ruleValue.length)
      this.formDynamic.ruleName = ''
      this.isBtn = false
      this.attrsName = ''
      this.attrsVal = ''
    },
    // 规格取消
    offAttrName() {
      this.isBtn = false
      this.attrsName = ''
      this.attrsVal = ''
    },
    // 添加属性名称
    createAttrName() {
      if (this.attrsName && this.attrsVal) {
        const data = {
          attrName: this.attrsName,
          attrValue: [
            this.attrsVal
          ]
        }
        this.formDynamic.ruleValue.push(data)
        const hash = {}

        // 判断是否已经存在
        this.formDynamic.ruleValue.reduce((item, next) => {
          hash[next.value] ? '' : hash[next.value] = true && item.push(next)
          return item
        }, [])

        this.attrsName = ''
        this.attrsVal = ''
        this.isBtn = false
      } else {
        this.$message.warning('请填写完整规格名称！')
      }
    }
  }
}
</script>

<style lang="scss" scope>
  .upload-form {
    &.el-message-box {
      border: none;
      min-width: 950px;
      .el-message-box__header {
        border-bottom: 1px solid #e8eaec;
      }
    }
  }

  @media (max-width: 767px) {
    .upload-form {
      &.el-message-box {
        min-width: auto;
        width: auto!important;
        margin: 10px;
      }
    }
  }

  .attrFrom {
    .acea-row {
      display: flex;
      align-items: center;
    }
    .footer {
      display: flex;
      justify-content: flex-end;
    }
    // 规格添加input框
    .input-new-tag {
      width: 90px;
      margin-right: 10px;
      vertical-align: middle;
    }
  }
</style>
